# 导包
import tornado.web

# 服务器
from tornado import httpserver

# 导入基础类
from base import BaseHandler

# 导入数据库操作类
from db import database,User,myser,Comment

# 异步执行库
import peewee_async


# 导入用户视图
from user_view import UserHandler,EmailActive,EmailBack,EmailCode,PhoneLogin,GiteeBack,UserInfo,MyCode,DingdingBack,GetUrl,WeiBoBack,Upload

# 导入帖子视图
from sub_view import SubjectView,AtUser,Img,FlowView,OneSub,CommentView

from playhouse.shortcuts import model_to_dict

from tools import send_mail

import json

import os

# 设置tornado静态文件夹目录

static_path = os.path.join(os.path.dirname(__file__),"static")






class SinaFirstHandler(BaseHandler):

    async def get(self):

        #微博接口地址
        weibo_auth_url = "https://api.weibo.com/oauth2/authorize"
        #回调网址
        redirect_url = "http://127.0.0.1:8888/weibo_back/"
        #应用id
        client_id = 3440988304
        #组合url
        auth_url = weibo_auth_url + "?client_id={client_id}&redirect_uri={re_url}".format(client_id=client_id,re_url=redirect_url)
        self.redirect(auth_url)


from peewee import fn

# 类视图
class TestHandler(BaseHandler):

	# 声明异步
	async def get(self):

		# 接收参数
		num = self.get_argument("num",10)

		# 获取余额
		# users = await self.application.objects.execute(Comment.select(Comment.sid,fn.COUNT(Comment.id).alias('ct')).group_by(Comment.sid))

		#await send_mail("123","123","123","123")

		# 异步获取多个
		#users = await self.application.objects.get(User.select().get())
		#print(users)
		#users = myser(users,many=True)
		# users = [myser(x) for x in users]
		# print(users)
		# users = User.select()

		# for x in users:
		# 	print(x.ct,x.sid)
		

		#print(user.num)

		# 添加数据
		#user = await self.application.objects.create(User,username="异步数据",age=20)

		# 修改数据
		#user.num = 500
		#await self.application.objects.update(user)

		# 异步删除
		#await self.application.objects.delete(user)

		#res = User.create(username="测试账号",age=20,phone="123321231")

		# 修改余额
		#user.num = user.num + int(num)
		#user.save()
		#await self.application.objects.update(user)

		#data = json.loads(json.dumps(model_to_dict(user),default=str))

		#print(data)

		return self.write({'code':200,'msg':'123'})

	# async def post(self):

	# 	# 接收参数
	# 	id = self.get_argument("id",None)

	# 	print(id)

	# 	return self.write({'code':200,'msg':'hello world','id':id})


# 执行tornado
# 执行方法
def main():
	# 实例化tornado对象
	app = tornado.web.Application(

		handlers=[

			# 首页
			(r'/',TestHandler),

			# 用户模块
			(r'/user/',UserHandler),

			# 邮箱激活
			(r'/emailactive/',EmailActive),
			(r'/emailback/',EmailBack),
			(r'/emailcode/',EmailCode),
			(r'/phonelogin/',PhoneLogin),
			(r'/geturl/',GetUrl),
			(r'/gitee_back/',GiteeBack),
			(r'/dingding_back/',DingdingBack),
			(r'/weibo_back/',WeiBoBack),
			(r'/userinfo/',UserInfo),
			(r'/mycode/',MyCode),
			(r'/upload/',Upload),

			(r'/sub/',SubjectView),
			(r'/atuser/',AtUser),
			(r'/img/',Img),
			(r'/flow/',FlowView),
			(r'/onesub/',OneSub),
			(r'/comment/',CommentView),

		],static_path=static_path,debug=True
	)
	# 将异步数据库操作，注入tornado
	app.objects = peewee_async.Manager(database)
	# 声明服务器
	server = httpserver.HTTPServer(app,xheaders=True)
	# 指定端口
	server.listen(8888)
	# 执行事件循环 ioloop
	tornado.ioloop.IOLoop.instance().start()

if __name__ == '__main__':
	print("服务已经启动!")
	main()